<!DOCTYPE html>
<html lang="en" dir="ltr">
    <head>
        <meta charset="utf-8">
        <title>动态绑定style</title>
    </head>
    <style media="screen">
        .active {
            color: red
        }
    </style>
    <body>
        <div id="app">
            <ul>
                <li v-for="(item, index) in movies" :class="{active: clickIndexes.contains(index)}"
                    @click='changeColor(index)'>{{index}} - {{item}}</li>
            </ul>


        </div>
    </body>
    <script src="../js/vue.js" charset="utf-8"></script>
    <script type="text/javascript">
        Array.prototype.remove = function(item) {
            if (this.length === 0) return false;
            let n = 0;
            for (let i = 0;i < this.length;i++) {
                if (this[i] !== item) {
                    this[n++] = this[i];
                }
            }
            if (this.length === n) return false;
            else {
                this.splice(n); // 触发Vue响应式
                return true;
            }
        }

        Array.prototype.contains = function(item) {
            for (let i = 0;i < this.length;i++) {
                if (this[i] === item) {
                    return true;
                }
            }
            return false;
        }

        const app = new Vue({
            el: '#app',
            data: {
                movies: ['海绵宝宝', '海王', '龙城飞将'],
                clickIndex: -1,
                clickIndexes: []
            },
            methods: {
                changeColor: function(index) {
                    // console.log(index);
                    this.clickIndex = index;
                    if (!this.clickIndexes.remove(index)) {
                        this.clickIndexes.push(index);
                    }
                    // this.clickIndexes.sort(); // 触发动态更新视图
                    // console.log(this.clickIndexes);
                }
            }
        });
    </script>
</html>
